package com.orange.zkcase3;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

/**
 * Description: Curator 框架实现分布式锁案例
 */
public class CuratorLockTest {
    public static void main(String[] args) {
        //创建分布式锁1
        InterProcessMutex lock1 = new InterProcessMutex(getCuratorFramework(), "/locks");

        //创建分布式锁2
        InterProcessMutex lock2 = new InterProcessMutex(getCuratorFramework(), "/locks");

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取到锁
                    lock1.acquire();
                    System.out.println("线程1 获取到锁");
                    //测试锁重入
                    lock1.acquire();
                    System.out.println("线程1 再次获取到锁");

                    Thread.sleep(3 * 1000);

                    //释放锁
                    lock1.release();
                    System.out.println("线程1 释放锁");

                    lock1.release();
                    System.out.println("线程1 再次释放锁");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //获取到锁
                    lock2.acquire();
                    System.out.println("线程2 获取到锁");
                    //测试锁重入
                    lock2.acquire();
                    System.out.println("线程2 再次获取到锁");

                    Thread.sleep(3 * 1000);

                    //释放锁
                    lock2.release();
                    System.out.println("线程2 释放锁");

                    lock2.release();
                    System.out.println("线程2 再次释放锁");
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

    /**
     * 分布式锁初始化
     */
    private static CuratorFramework getCuratorFramework() {
        //重试策略，初试时间 3秒，重试3次
        ExponentialBackoffRetry policy = new ExponentialBackoffRetry(3000, 3);
        //通过工厂创建Curator
        CuratorFramework client = CuratorFrameworkFactory
                .builder()
                //zookeeper server列表
                .connectString("192.168.147.128:2181,192.168.147.129:2181,192.168.147.130:2181")
                //connection超时时间
                .connectionTimeoutMs(20000)
                //session超时时间
                .sessionTimeoutMs(20000)
                .retryPolicy(policy).build();
        //启动客户端
        client.start();

        System.out.println("zookeeper 初始化完成...");
        return client;
    }
}
